package com.wanmait.community.controller;

import com.github.pagehelper.PageInfo;
import com.wanmait.community.aop.OperationLogInfo;
import com.wanmait.community.entity.AdminRepair;
import com.wanmait.community.entity.BeforeRepairPic;
import com.wanmait.community.service.AdminRepairService;
import com.wanmait.community.service.BeforeRepairPicService;
import com.wanmait.community.service.UserRepairService;
import com.wanmait.community.util.AjaxResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("adminRepair")
public class AdminRepairController {
    @Resource
    private AdminRepairService adminRepairService;
    @Resource
    private UserRepairService userRepairService;
    @Resource
    private BeforeRepairPicService beforeRepairPicService;
    @PostMapping("list")
    public AjaxResult list(@RequestBody AdminRepair adminRepair,Integer pageNum) {
        System.out.println("后端接收的搜索栏对象==>"+adminRepair);
        Integer pageSize = 3;
        PageInfo<AdminRepair> list = adminRepairService.findAll(adminRepair,pageNum,pageSize);
        return AjaxResult.success().put("list", list);
    }
    @PostMapping("handleRepair")//处理报修，就是修改维修说明、维修时间、维修费用等
    @OperationLogInfo("物业处理维修了一条报修记录")
    public AjaxResult handleRepair(@RequestBody AdminRepair adminRepair) {
        System.out.println("后端收到的修理信息==》"+adminRepair);
        adminRepairService.updateHandleRepair(adminRepair);
        return AjaxResult.success();
    }
    //查单个adminRepair对象，供修改时显示原数据
    @GetMapping("{id}")
    public AjaxResult findContentById(@PathVariable Integer id) {
        AdminRepair adminRepair = adminRepairService.findAdminRepairById(id);
        return AjaxResult.success().put("adminRepair",adminRepair);
    }
    //其他userRepair表单内容交到这
    @PostMapping("insertUserRepair")
    @OperationLogInfo("业主添加了一条报修信息")
    public AjaxResult insertUserRepair(@RequestBody AdminRepair adminRepair) {
        String firstUploadImages = this.getFirstUploadImage();//获取首次上传文件名
        adminRepairService.insertAdminRepair(adminRepair,firstUploadImages);
        return AjaxResult.success("添加报修信息成功");
    }
    @PostMapping("userUpdateAdminRepair")//业主修改自己提交过的报修信息userRepair，同时修改adminRepair的更新人和更新时间
    @OperationLogInfo("业主修改了一条报修信息")
    public AjaxResult userUpdateAdminRepair(@RequestBody AdminRepair adminRepair) {
        //1.先根据adminRepair.id查单个beforeRepairPic
        BeforeRepairPic beforeRepairPic = beforeRepairPicService.findBRPByAdminRepairId(adminRepair.getId());
        //2.获取首次上传文件名，将用来去修改之前的beforeRepairPic
        String firstUploadImages = this.getFirstUploadImage();
        //3.决定使用新图片还是保留原图片,假设前端在被删除时会设置某个标志
        String finalImage;
        if(Boolean.TRUE.equals(adminRepair.isImageDeleted())){//情况1，删除了原有图片
            finalImage = null;
        }
        else if(firstUploadImages!=null){//情况2，换了新图片
            finalImage = firstUploadImages;
        }
        else{//情况3，保持原图片
            finalImage = (beforeRepairPic!=null)?beforeRepairPic.getBeforePic():null;
        }
        //4.在后端设置updateTime（因为前端的其他业务需求修改了时间格式，传到后端为当天0点）所以在后端设置updateTime
        Date now = new Date();// 获取系统当前时间
        adminRepair.setUpdateTime(now);//设置更新时间
        adminRepair.getBeforeRepairPic().setUpdateTime(now);//设置更新时间
        //5.设置维修前图片（可能是新图片或原有图片）
        if(adminRepair.getBeforeRepairPic()==null){
           adminRepair.setBeforeRepairPic(new BeforeRepairPic());
        }
        adminRepair.getBeforeRepairPic().setBeforePic(finalImage);//不需要else
        //6.清除上传缓存
        this.firstUploadImage = null;
        //7.去数据库修改
        adminRepairService.updateAdminRepairById(adminRepair);//改adminRepair表
        userRepairService.updateUserRepairByAdminRepairId(adminRepair.getUserRepair());//改userRepair表
        BeforeRepairPic beforeRepairPicNew = adminRepair.getBeforeRepairPic();
        //给beforeRepairPic对象设置updateBy和updateTime值
        beforeRepairPicNew.setUpdateBy(adminRepair.getUpdateBy());
        beforeRepairPicNew.setUpdateTime(adminRepair.getUpdateTime());
        beforeRepairPicService.updateBeforeRepairPicByAdminRepairId(beforeRepairPicNew);//改beforeRepairPic表
        return AjaxResult.success("修改报修信息成功");
    }
    // 因为要存设备维修前图片(beforeRepairPic.beforePic)一张，而编辑器可上传多张，则只取第一次上传的，如果没上传图片，则存null，
    private String firstUploadImage = null;
    @Nullable//加这个注解是明确告诉调用方：此方法可能返回 null，调用方应该检查返回值。（不加会警告）
    public String getFirstUploadImage() {//供其他方法调用
        return this.firstUploadImage;
    }
    @OperationLogInfo("在线编辑器图片上传")
    @PostMapping("uploadWangEditorPic")//编辑器图片上传
    public Map<String, Object> uploadWangEditorPic(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();//因为编辑器上传文件返回格式要求，这里只能用map
        try {
            String path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadImages/";//文件存储物理路径，在编译时把文件复制到tag
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());//唯一文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + "." + ext;//生成新文件名
            file.transferTo(new File(path + File.separator + fileName));//保存文件
            //保存第一次上传的新文件名
            if(this.firstUploadImage == null) {
                this.firstUploadImage = fileName;
            }
            map.put("errno", 0);//上传成功错误码为0，编辑器数据处理格式要求
            Map<String,String>data = new HashMap<>();//data里面还是对象，对象里面才有url，所以再建一个map
            String basePath = request.getRequestURL().toString().replace(request.getRequestURI(),"");//获取根路径,在URL中把uri替换为""
            data.put("url", basePath + "/static/uploadImages/"+fileName);//动态路径
            map.put("data", data);
        } catch (IOException e) {
            map.put("errno", 1);//上传成功错误码为1
            map.put("message", "图片上传失败");//失败信息
        }
        return map;
    }
    @PostMapping("delete")
    @OperationLogInfo("业主删除了一条报修记录")
    public AjaxResult delete(@RequestBody AdminRepair adminRepair) {
        adminRepairService.deleteAdminRepairById(adminRepair.getId());
        beforeRepairPicService.deleteBeforeRepairPicByAdminRepairId(adminRepair.getId());
        userRepairService.deleteUserRepairByAdminRepairId(adminRepair.getId());
        return AjaxResult.success("删除了一条报修记录");
    }
    //自定义异常处理，文件大小异常就走这
    @Value("${spring.servlet.multipart.max-file-size}")//注入单个文件上传大小的值
    private String maxFileSize;
    //在线编辑器上传图片异常处理,这是按在线编辑器格式要求自定义一个关于文件大小超限的异常处理方法；
    @OperationLogInfo("业主报修信息上传图片大小异常")
    @ExceptionHandler(value= MaxUploadSizeExceededException.class)
    public Map handleException(MaxUploadSizeExceededException exception) {
        Map<String, Object> map = new HashMap<>();
        map.put("errno", 1);//上传成功错误码为1
        map.put("message", "上传文件大小超出，最大允许：" + maxFileSize);//失败信息
        return map;
    }
}
